﻿#include "windowlogin.h"

#include "appcommon.h"
#include "ui_windowlogin.h"
#include "config/appconfig.h"

#include <QMessageBox>
#include <QTimer>

#include <util/aes_util.h>

WindowLogin::WindowLogin(QWidget *parent) :
    QMainWindow(parent), ui(new Ui::WindowLogin) {
    ui->setupUi(this);

    setWindowTitle("VPN 登录");

    connect(&m_main, &MainWindow::needLogout, this, &WindowLogin::tryLogout);
    connect(&m_client, &SoftEtherClient::stateChanged, this, &WindowLogin::stateChanged);
    connect(&m_client, &SoftEtherClient::loginFinish, this, &WindowLogin::loginFinish);
    connect(&m_client, &SoftEtherClient::logoutOK, this, &WindowLogin::logoutOK);

    m_connected = false;
    loadConfig();
}

WindowLogin::~WindowLogin() {
    delete ui;
}

void WindowLogin::tryLogin() {
    QString serverAddress = ui->txtHostIP->text().trimmed();
    QString username = ui->txtUserName->text().trimmed();
    QString password = ui->txtPassword->text().trimmed();
    QString hubName = ui->txtHubName->text().trimmed();
    QString staticIP = "";

    if(serverAddress.isEmpty()||username.isEmpty()||password.isEmpty()||hubName.isEmpty()){
        QMessageBox::warning(this, tr("参数检查"), tr("请填写：服务器地址、用户名、密码、HUB名称"));
        resetForm();
        return;
    }


    bool serverIPValid = AppCommon::isValidIPPort(serverAddress);
    if (!serverIPValid) {
        QMessageBox::warning(this, tr("参数检查"), tr("服务器地址无效"));
        resetForm();
        return;
    }

    m_client.connectVpn(serverAddress, hubName, username, password, staticIP);
}

bool WindowLogin::tryLogout() {
    cleanVpn();
    m_main.hide();
    ui->lblInfo->setText("");
    AppCommon::showWindowToCenter(this);
    return true;
}

void WindowLogin::cleanVpn() {
    if(m_connected){
        m_client.clean();
    }
    resetForm();
}

void WindowLogin::showForm()
{
    if(m_connected){
        m_main.show();
    }else{
        this->show();
    }
}

void WindowLogin::closeForm()
{
    m_main.setNeedExit(true);
    m_main.close();
    this->close();
}

void WindowLogin::stateChanged(QString msg) {
    ui->lblInfo->setText(msg);
}

void WindowLogin::loginFinish(bool loginOK) {
    if (loginOK) {
        QString serverAddress = ui->txtHostIP->text().trimmed();
        QString username = ui->txtUserName->text().trimmed();
        QString password = ui->txtPassword->text().trimmed();
        QString hubName = ui->txtHubName->text().trimmed();
        QString staticIP = "";

        m_main.setVpnInfo(serverAddress, hubName, username, m_client.getVpnIP(), m_client.getConnectTime());
        AppCommon::showWindowToCenter(&m_main);
        this->hide();

        {
            AppConfig &config = AppConfig::instance();
            {
                config.setParams(AppConfigItems::SystemParams::HostIP, serverAddress);
                config.setParams(AppConfigItems::SystemParams::UserName, username);
                config.setParams(AppConfigItems::SystemParams::HubName, hubName);
                if (!password.isEmpty()) {
                    QString encryptPassword = AESUtil::encryptBase64(password);
                    config.setParams(AppConfigItems::SystemParams::Password, encryptPassword);
                }
            }
            {
                config.setBoolParams(AppConfigItems::SystemParams::SavePassword, ui->chbSavePassword->isChecked());
                config.setBoolParams(AppConfigItems::SystemParams::AutoLogin, ui->chbAutoLogin->isChecked());
            }

            config.saveConfig();
        }
        m_connected = true;
        stateChanged("登录VPN[成功]");
    }else{
        stateChanged("登录VPN[失败]");
    }
    resetForm();
}

void WindowLogin::logoutOK() {
}

void WindowLogin::on_btnLogin_clicked() {
    ui->btnLogin->setEnabled(false);
    ui->txtHostIP->setEnabled(false);
    ui->txtUserName->setEnabled(false);
    ui->txtPassword->setEnabled(false);
    ui->txtHubName->setEnabled(false);
    tryLogin();
}


bool WindowLogin::loadConfig() {
    AppConfig &config = AppConfig::instance();

    {
        ui->chbSavePassword->setChecked(config.getBoolParams(AppConfigItems::SystemParams::SavePassword, false));
        ui->chbAutoLogin->setChecked(config.getBoolParams(AppConfigItems::SystemParams::AutoLogin, false));


        QString serverAddress =config.getParams(AppConfigItems::SystemParams::HostIP, "");
        QString username =config.getParams(AppConfigItems::SystemParams::UserName, "");
        QString hubName= config.getParams(AppConfigItems::SystemParams::HubName, "");

        ui->txtHostIP->setText(serverAddress);
        ui->txtUserName->setText(username);
        ui->txtHubName->setText(hubName);

        QString password = config.getParams(AppConfigItems::SystemParams::Password, "").trimmed();
        if (password.isEmpty()) {
            ui->txtPassword->setPlaceholderText(tr("尚未配置密码"));
            ui->txtPassword->setToolTip(tr("尚未配置密码"));
            ui->txtPassword->clear();
        } else {
            ui->txtPassword->setPlaceholderText(tr("已配置密码"));
            ui->txtPassword->setToolTip(tr("已配置登录密码，如需变更，请重新填写密码"));

            password = AESUtil::decryptBase64(password.toUtf8());
            ui->txtPassword->setText(password);
        }

        if(ui->chbAutoLogin->isChecked()){
            if(!(serverAddress.isEmpty()||username.isEmpty()||password.isEmpty()||hubName.isEmpty())
                    && AppCommon::isValidIPPort(serverAddress)){
                QTimer::singleShot(1000, this, [this]() {
                    on_btnLogin_clicked();
                });
            }
        }
    }
    return true;
}

void WindowLogin::resetForm()
{
    ui->btnLogin->setEnabled(true);
    ui->txtHostIP->setEnabled(true);
    ui->txtUserName->setEnabled(true);
    ui->txtPassword->setEnabled(true);
    ui->txtHubName->setEnabled(true);
}


void WindowLogin::on_chbAutoLogin_clicked()
{
    if(ui->chbAutoLogin->isChecked()){
        ui->chbSavePassword->setChecked(true);
    }
}
